package com.coffee.netty.connection;

import cn.hutool.core.util.RandomUtil;
import com.coffee.concurrent.CoffeeScheduler;
import com.coffee.netty.util.ExecutorManager;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author songkui
 * @since 2024/8/6
 */
public class ReconnectionHandler {
    private static final InternalLogger logger = InternalLoggerFactory.getInstance(ReconnectionHandler.class);

    public void reconnect(ConnectionFactory connectionFactory, Connection connection){
        logger.info("Reconnect connection: {}", connection);
        connect(connectionFactory, connection);
    }

    public  void disconnectReconnect(ConnectionFactory connectionFactory, Connection connection){
        logger.info("Disconnect Reconnect connection: {}", connection);
        connect(connectionFactory, connection);
    }


    private void connect(ConnectionFactory connectionFactory, Connection connection){
        if (OnlineType.OffLine.equals(connection.getOnlineType())){
            logger.info("Connection is offline don`t reconnect");
            return;
        }

        if (null != connection.getReconnectSchedule()){
            CoffeeScheduler.cancelScheduled(connection.getReconnectSchedule());
        }

        long delay =  Math.max(connection.getReconnectTime(), 30000L);
        long randDelay = RandomUtil.randomLong(delay - 1000,  delay + 1000);
        ScheduledFuture<?>  reconnectSchedule = ExecutorManager.getInstance().getDefaultScheduler().schedule(()-> {
            try {
                connectionFactory.connect(connection);
            } catch (Exception e) {
                logger.error("Reconnect is failure connection {}, error message: {}", connection, e.getMessage());
            }
        }, randDelay, TimeUnit.MILLISECONDS, ExecutorManager.getInstance().getDefaultExecutor());
        connection.setReconnectSchedule(reconnectSchedule);
    }


}
